package com.yanqu.road.server.manager.systemgroup.newmonopolymkt;

import com.yanqu.road.dao.impl.nenmonopolymarket.resgrab.NewMonopolyMarketResGrabFinishDataDaoImpl;
import com.yanqu.road.dao.impl.nenmonopolymarket.resgrab.NewMonopolyMarketResGrabPointDataDaoImpl;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.config.battle.PatronsBattleDetail;
import com.yanqu.road.entity.config.beauty.BeautyInfo;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.systemgroup.ResourceServerGroup;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.CrossNewMonopolyMarketUserData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.NewMonopolyMarketNoticeData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.NewMonopolyMarketServerGroup;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.config.NewMonopolyMarketResConfigData;
import com.yanqu.road.entity.log.cross.newMonopolyMarket.log.NewMonopolyMarketResGrabRobLogData;
import com.yanqu.road.entity.log.cross.newMonopolyMarket.log.NewMonopolyMarketSearchLogData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.resgrab.*;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.BattlePb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.newmonopolymkt.NewMonopolyMarketProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.config.BeautyMgr;
import com.yanqu.road.server.manager.config.PatronsMgr;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.NewMonopolyMarketCommonMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossNewMonopolyMarketResRob {

    /**
     * 大管家
     */
    private CrossNewMonopolyMarketGroup monopolyMarket;

    /**
     * 分组资源
     */
    private Map<Integer, NewMonopolyMarketResGrab> marketResGrabMap = new HashMap<>();

    /**
     * 玩家采集完成的未领取奖励
     */
    public Map<Long, List<NewMonopolyMarketResGrabFinishData>> userResGrabFinishMap = new ConcurrentHashMap<>();

    /**
     * 玩家采集完成的未加入排行榜的数值 （排行榜用） k：id
     */
    public Map<Long, NewMonopolyMarketResGrabFinishData> userResGrabRankMap = new ConcurrentHashMap<>();

    /**
     * 临时采集的奖励 入库用
     */
    public List<NewMonopolyMarketResGrabFinishData> tempResGrabFinishList = new ArrayList<>();

    public CrossNewMonopolyMarketResRob(CrossNewMonopolyMarketGroup monopolyMarket) {
        this.monopolyMarket = monopolyMarket;
        for (Map.Entry<Integer, ResourceServerGroup> entry : monopolyMarket.getWeekStateData().getInnerGroupList().entrySet()) {
            ResourceServerGroup serverGroup = entry.getValue();
            NewMonopolyMarketResGrab resGrab = new NewMonopolyMarketResGrab(serverGroup.getGroupId(), serverGroup.getResType());
            boolean init = initMap(resGrab, serverGroup);
            if(init){
                CrossNewMonopolyMarketMgr.getLogger().info("初始地图：周：{} 分组：{} 资源分组：{} 分组类型：{}", monopolyMarket.getWeekStateData().getWeekId(), monopolyMarket.getGroupId(), entry.getKey(), entry.getValue().getGroupType());
            }
            marketResGrabMap.put(serverGroup.getGroupId(), resGrab);
        }
    }

    public void loadData() {

        int weekId = monopolyMarket.getWeekStateData().getWeekId();
        int systemGroupId = monopolyMarket.getWeekStateData().getSystemGroupId();
        List<NewMonopolyMarketResGrabFinishData> finishDataList = new NewMonopolyMarketResGrabFinishDataDaoImpl().getNewMonopolyMarketResGrabFinishData(weekId, systemGroupId);

        // 资源结算奖励
        for (NewMonopolyMarketResGrabFinishData item : finishDataList) {
            if (!item.getIsJoinRank()) {
                userResGrabRankMap.put(item.getId(), item);
            }
            if (!item.getIsReceive()) {
                List<NewMonopolyMarketResGrabFinishData> list = userResGrabFinishMap.computeIfAbsent(item.getUserId(), k -> new ArrayList<>());
                list.add(item);
            }
        }

        //动态生成地图
        for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : getMarketResGrabMap().entrySet()) {
            NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();
            initMap(resGrab);
        }

        // 加载资源点
        List<NewMonopolyMarketResGrabPointData> list = new NewMonopolyMarketResGrabPointDataDaoImpl().getNewMonopolyMarketResGrabPointData(weekId, systemGroupId);
        int now = DateHelper.getCurrentSecond();
        for (NewMonopolyMarketResGrabPointData data : list) {
            NewMonopolyMarketResGrab resGrab = getMarketResGrabMap().get(data.getResGroupId());
            NewMonopolyMarketResGrabPointInfo pointInfo = new NewMonopolyMarketResGrabPointInfo(data);
            resGrab.pointsMap.put(data.getPosIndex(), pointInfo);
            if(data.getUserId() > 0){
                // 尝试结算 据点
                if(pointInfo.baseInfo.getUserId() > 0){
                    int settlementTime = getPointEndTime(resGrab, pointInfo);
                    if(settlementTime != -1 && now >= settlementTime){
                        normalSettlement(resGrab, pointInfo,false,settlementTime);
                    }else {
                        addCurPointInfo(resGrab, pointInfo);
                    }
                }
            }
        }

    }

    public void saveData(){

        // 资源结算 奖励
        List<NewMonopolyMarketResGrabFinishData> resGrabFinishList;
        synchronized (tempResGrabFinishList){
            resGrabFinishList = new ArrayList<>(tempResGrabFinishList);
            tempResGrabFinishList.clear();
        }
        for(NewMonopolyMarketResGrabFinishData item : resGrabFinishList){
            if (item.isUpdateOption()) {
                new NewMonopolyMarketResGrabFinishDataDaoImpl().update(item);
            } else if (item.isInsertOption()) {
                new NewMonopolyMarketResGrabFinishDataDaoImpl().add(item);
            }
        }

        for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : getMarketResGrabMap().entrySet()) {
            NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();

            List<NewMonopolyMarketResGrabPointInfo> pointInfoTempList = new ArrayList<>();
            synchronized (resGrab.updateAndAddPointInfoSet){
                pointInfoTempList.addAll(resGrab.updateAndAddPointInfoSet);
                resGrab.updateAndAddPointInfoSet.clear();
            }
            List<NewMonopolyMarketResGrabPointData> updatePointInfoList = new ArrayList<>();
            List<NewMonopolyMarketResGrabPointData> addPointInfoList = new ArrayList<>();
            for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfoTempList){
                if (pointInfo.baseInfo.isUpdateOption()) {
                    updatePointInfoList.add(pointInfo.baseInfo);
                } else if (pointInfo.baseInfo.isInsertOption()) {
                    addPointInfoList.add(pointInfo.baseInfo);
                }
            }
            if(addPointInfoList.size() > 0){
                new NewMonopolyMarketResGrabPointDataDaoImpl().batchAdd(addPointInfoList);
            }
            if(updatePointInfoList.size() > 0){
                new NewMonopolyMarketResGrabPointDataDaoImpl().batchUpdate(updatePointInfoList);
            }
        }
    }

    public boolean refresh(int time){
        //每日重置资源点，周一0点最后一次重置，周二0点就不需要了（已经是不同周了）
        if(DateHelper.getDiffDayNum(monopolyMarket.getWeekStateData().getKingResGrabRefreshTime()) != 0 ){
            for (Map.Entry<Integer, NewMonopolyMarketResGrab> grabEntry : getMarketResGrabMap().entrySet()) {
                NewMonopolyMarketResGrab resGrab = grabEntry.getValue();
                for (NewMonopolyMarketResGrabPointInfo pointInfo : resGrab.pointsMap.values()){
                    clearPointInfo(resGrab, pointInfo,true, time);
                    synchronized (resGrab.updateAndAddPointInfoSet){
                        resGrab.updateAndAddPointInfoSet.add(pointInfo);
                    }
                }
            }
            monopolyMarket.getWeekStateData().setKingResGrabRefreshTime(time);
            return true;
        }
        return false;
    }

    /**
     * 清空位置信息
     * @param resGrab
     * @param pointInfo
     */
    public void clearPointInfo(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo, boolean isCalRemainTime, int time){
        pointInfo.baseInfo.setUserId(0);
        if(isCalRemainTime){
            pointInfo.baseInfo.setRemainTime(calResTotalTime(resGrab, pointInfo.baseInfo.getPosIndex()));
        }else {
            pointInfo.baseInfo.setRemainTime(0);
        }
        pointInfo.baseInfo.setResetTime(time);
        pointInfo.baseInfo.setReceiveLastTime(0);
        pointInfo.baseInfo.setProduceRewardLastTime(0);
        pointInfo.baseInfo.setSeatTime(0);
        pointInfo.baseInfo.setEndTime(0);
        pointInfo.baseInfo.getObjectInfoList().clear();
        pointInfo.objectInfoMap.clear();
        pointInfo.userSet.clear();
        pointInfo.baseInfo.setChangeTime(time);
        pointInfo.baseInfo.setServerId(0);
        initNpcInfo(resGrab, pointInfo);
    }

    public boolean initMap(NewMonopolyMarketResGrab resGrab){
        ResourceServerGroup resourceServerGroup = monopolyMarket.getWeekStateData().getInnerGroupList().get(resGrab.getResGroupId());
        if(resourceServerGroup == null){
            return false;
        }
        return initMap(resGrab, resourceServerGroup);
    }

    /**
     * 初始地图
     * @param resGrab 资源分组
     * @param serverGroup 分组信息
     */
    public boolean initMap(NewMonopolyMarketResGrab resGrab, ResourceServerGroup serverGroup) {
        if(resGrab.map == null){
            NewMonopolyMarketResGrabMap map = initResMap(resGrab, serverGroup, true);
            if(map == null){
                return false;
            }
            resGrab.map = map;
            return true;
        }
        if(Config.isDebug()){
//            NewMonopolyMarketResGrabMap map = initResMap(resGrab, serverGroup, false);
//            if(map != null){
//                Map<Integer, Integer> lvNumMap = new HashMap<>();
//                for (int lv : map.indexLevelList) {
//                    int num = lvNumMap.getOrDefault(lv, 0);
//                    lvNumMap.put(lv, 1 + num);
//                }
//                for (Map.Entry<Integer, Integer> entry : lvNumMap.entrySet()) {
//                    if(entry.getKey() > 0) {
//                        CrossNewMonopolyMarketMgr.getLogger().info("资源等级：{}，{}", entry.getKey(), entry.getValue());
//                    }
//                }
//            }
        }
        return false;

    }

    public NewMonopolyMarketResGrabMap initResMap(NewMonopolyMarketResGrab resGrab, ResourceServerGroup serverGroup, boolean showLog){

        //活跃人数
        int activeNum = monopolyMarket.getGroupActiveNum();
        if(activeNum == 0){
            return null;
        }
        //总资源点
        int totalNum = 0;
        //各等级资源点的數量
        Map<Integer, Integer> pointLvNumMap = new HashMap<>();

        List<Integer> param2List = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_RESOURCE_PARAM_2, "\\|");

        //各等级队伍系数
        List<Integer> param1List = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_RESOURCE_PARAM_1, "\\|");

        //同类分组的數量（各大、中、小跨服同类资源分组的數量）
        int groupNum = monopolyMarket.getGroupNumByLevelAndType(serverGroup.getGroupType(), serverGroup.getResType());

        List<Integer> configMinLimitList = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_RESOURCE_MIN_NUM, "\\|");

        //资源配置，计算各等级资源点的數量
        List<NewMonopolyMarketResConfigData> resConfigDataList = CrossNewMonopolyMarketConfigMgr.getResConfigListByType(serverGroup.getResType());
        for (NewMonopolyMarketResConfigData configData : resConfigDataList) {
            //过滤等级
            if(configData.getBelongBase() != serverGroup.getGroupType()){
                continue;
            }
            int lv = configData.getLevel();
            int pointNum = BigDecimal.valueOf(activeNum).multiply(BigDecimal.valueOf(param2List.get(lv - 1))).multiply(BigDecimal.valueOf(param1List.get(lv - 1))).
                    divide(BigDecimal.valueOf(groupNum).multiply(BigDecimal.valueOf(1000 * 1000)), 0, BigDecimal.ROUND_UP).intValue();
            CrossNewMonopolyMarketMgr.getLogger().info("res grab weekId {} groupId {}，groupNum {}，活跃玩家数量 {}, 资源点 等级 {} 数量 {}", this.monopolyMarket.getWeekStateData().getWeekId(),
                    this.monopolyMarket.getGroupId(), groupNum, activeNum, lv, pointNum);

            //最小值对比
            int minLimit = configMinLimitList.get(lv - 1);
            minLimit = minLimit / groupNum;
            pointNum = Math.max(minLimit, pointNum);

            pointLvNumMap.put(lv, pointNum);
            totalNum += pointNum;
        }
        if(totalNum == 0){
            CrossNewMonopolyMarketMgr.getLogger().info("res grab weekId {} groupId {} totalNum 0", monopolyMarket.getWeekStateData().getWeekId(),
                    monopolyMarket.getGroupId());
            return null;
        }

        NewMonopolyMarketResGrabMap map = NewMonopolyMarketCommonMgr.initResGrabMap(serverGroup.getResType(), totalNum,
                new NewMonopolyMarketServerGroup(monopolyMarket.getWeekStateData().getWeekId(), serverGroup), resConfigDataList, pointLvNumMap, showLog);

        return map;
    }

    public long getNpcBlood(int resGroupId, int type, int level){
        return monopolyMarket.getNpcBlood(type, level);
    }


    //-----------------------

    /**
     * 批量领取据点奖励
     * @param userId
     * @param serverId
     * @param list
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardToGameServerMsg.Builder getPointReward(long userId,long serverId, List<NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardTemp> list){
        NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardToGameServerMsg.Builder resp = NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardToGameServerMsg.newBuilder();
        NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardRespMsg.Builder stcMsg = NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardRespMsg.newBuilder();

        int allRankCount = 0;
        synchronized (this){
            Property property = new Property();
            for (NewMonopolyMarketProto.NewMonopolyMarketGetPointRewardTemp item : list){
                // 领取奖励
                NewMonopolyMarketResGrab resGrab = getMarketResGrabMap().get(item.getResGroupId());
                if(resGrab != null){
                    int totalRewardNum = 0;
                    Set<NewMonopolyMarketResGrabPointInfo> pointInfos = resGrab.getUserPointSet(userId,false);
                    if(pointInfos != null){
                        for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfos){
                            // 加个保护
                            if(pointInfo.baseInfo.getUserId() != userId){
                                continue;
                            }
                            // 玩家正在采集的据点
                            if(item.getPosIndexList().contains(pointInfo.baseInfo.getPosIndex())){
                                // 判断是否能够被领取
                                NewMonopolyMarketResGrabReceiveResult receiveResult = receivePoint(resGrab, pointInfo);
                                if(receiveResult.getAddValue() > 0){
                                    totalRewardNum += receiveResult.getAddValue();
                                    resp.addAddRankList(builderMonopolyMarketAddRankValueEntity(receiveResult));
                                }
                                stcMsg.addTeamList(builderMonopolyMarketGetTeamEntity(pointInfo));
                            }
                        }
                    }
                    if(totalRewardNum > 0){
                        int goodsId = NewMonopolyMarketCommonMgr.getGoodsId(item.getType());
                        property.addProperty(new Property(goodsId, BigInteger.valueOf(totalRewardNum)));
                        allRankCount += totalRewardNum;
                    }
                }
            }
            if(property.getGoods().size() > 0){
                stcMsg.setRewards(PropertyHelper.parsePropertyToString(property));
            }
        }
        addUserRankValue(userId, allRankCount);
        stcMsg.setRet(0);
        resp.setStcMsg(stcMsg);
        return resp;
    }

    /**
     * 领取据点奖励
     * @param pointInfo
     * @return
     */
    private NewMonopolyMarketResGrabReceiveResult receivePoint(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketResGrabReceiveResult receiveResult = new NewMonopolyMarketResGrabReceiveResult();
        int now = DateHelper.getCurrentSecond();
        int rewardNum = 0;
        int pointEndTime = getPointEndTime(resGrab,pointInfo);
        if((now >= (pointInfo.baseInfo.getReceiveLastTime() + GameConfig.NEWMONOPOLYMARKET_GETREWARD_CD) && (pointInfo.baseInfo.getProduceRewardLastTime() > 0) && pointEndTime >= now)){
            // 表示领奖cd到了可以领奖，但不一定有奖励可以领
            NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(resGrab, pointInfo.baseInfo.getPosIndex());
            int rewardTime = now - pointInfo.baseInfo.getProduceRewardLastTime();
            // 采集单位数量
            int cd = NewMonopolyMarketCommonMgr.getResGrabPointCD(resGrab.type);
            int i = rewardTime / cd;
            if(i > 0){
                ResourceServerGroup serverGroup = monopolyMarket.getWeekStateData().getInnerGroupList().get(resGrab.getResGroupId());
                // 总采集的资源
                int rate = NewMonopolyMarketCommonMgr.calResRate(serverGroup.getServerList().size(), configData.rewardValue1, configData.rewardAdd1,configData.getId(), 1);
                rewardNum = i * rate;

                receiveResult.setAddValue(rewardNum);
                receiveResult.setStartTime(pointInfo.baseInfo.getProduceRewardLastTime());
                receiveResult.setTime(rewardTime);
                receiveResult.setType(resGrab.type);

                pointInfo.baseInfo.setReceiveLastTime(now);
                pointInfo.baseInfo.setProduceRewardLastTime(pointInfo.baseInfo.getProduceRewardLastTime() + i * cd);
                synchronized (resGrab.updateAndAddPointInfoSet){
                    resGrab.updateAndAddPointInfoSet.add(pointInfo);
                }
                broadcastMonopolyMarketResGrabRespMsg(pointInfo,pointInfo.baseInfo.getUserId());
            }
        }
        return receiveResult;
    }

    /**
     * 搜索
     * @param serverId
     * @param resGroupId
     * @param level
     * @param startPosIndex  不包含
     * @return
     */
    public NewMonopolyMarketProto.CrossNewMonopolyMarketResGrabSearchRespMsg.Builder search(long serverId, long playerId, int resGroupId, int level, int guanYin, int startPosIndex, boolean isEmpty){
        NewMonopolyMarketProto.CrossNewMonopolyMarketResGrabSearchRespMsg.Builder builder = NewMonopolyMarketProto.CrossNewMonopolyMarketResGrabSearchRespMsg.newBuilder();
        ResourceServerGroup serverGroup = monopolyMarket.getWeekStateData().getInnerGroupList().get(resGroupId);
        if(serverGroup == null || (serverGroup.getServerList().size() > 0 && !serverGroup.getServerList().contains(serverId))){
            builder.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return builder;
        }
        //关引
        List<Integer> consumeList = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_SEARCH_COST, "\\|");
        int needGuanYin = consumeList.get(serverGroup.getGroupType() - 1);
        if(needGuanYin > guanYin){
            builder.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return builder;
        }
        builder.setGuanYin(needGuanYin);
        NewMonopolyMarketResGrab resGrab = getMarketResGrabMap().get(resGroupId);
        if (resGrab == null) {
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_TYPE_NO_ERROR);
            return builder;
        }

        UserBaseInfo playerInfo = CrossUserMgr.getUserBaseInfo(playerId);
        List<Integer> npcList = new ArrayList<>();
        List<Integer> otherServerList = new ArrayList<>();
        List<Integer> sameServerList = new ArrayList<>();
        List<Integer> optionalList = new ArrayList<>();
        //遍历所有资源点，分类点位，信息可能滞后
        for (Map.Entry<Integer, Integer> entry : resGrab.map.indexLevelMap.entrySet()) {
            int index = entry.getKey();
            int lv = entry.getValue();
            if(lv == 0){
                continue;
            }
            //npc
            NewMonopolyMarketResGrabPointInfo pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, index, false);
            if(pointInfo == null || pointInfo.baseInfo.getUserId() == 0){
                npcList.add(index);
                continue;
            }
            if(pointInfo.baseInfo.getUserId() == playerId){
                continue;
            }
            //同商会
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(pointInfo.baseInfo.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            if(!StringUtils.isNullOrEmpty(playerInfo.getUnionUid()) && playerInfo.getUnionUid().equals(userBaseInfo.getUnionUid())){
                optionalList.add(index);
                continue;
            }
            //不同区服
            if(userBaseInfo.getServerId() != playerInfo.getServerId()){
                otherServerList.add(index);
                continue;
            }
            if(userBaseInfo.getServerId() == playerInfo.getServerId()){
                sameServerList.add(index);
            }
        }
        NewMonopolyMarketResGrabPointInfo pointInfo = null;
        if(npcList.size() > 0){
            if(new Random().nextInt(1000) < GameConfig.NEWMONOPOLYMARKET_SEARCH_PRO){
                pointInfo = randomPointInfo(resGrab, npcList);
            }
        }
        //npc 和 不同区服的优先级一样
//        npcList.addAll(otherServerList);
//        NewMonopolyMarketResGrabPointInfo pointInfo = randomPointInfo(resGrab, npcList);
        if(pointInfo == null){
            pointInfo = randomPointInfo(resGrab, otherServerList);
        }
        //保证npc有
        if(pointInfo == null){
            pointInfo = randomPointInfo(resGrab, npcList);
        }
        if(pointInfo == null){
            pointInfo = randomPointInfo(resGrab, sameServerList);
        }
        if(pointInfo == null){
            pointInfo = randomPointInfo(resGrab, optionalList);
        }
        if(pointInfo != null) {
            builder.addPointList(builderMonopolyMarketResGrabSearchPointEntity(pointInfo));
            builder.setRet(0);
            CrossAutoLogMgr.add(new NewMonopolyMarketSearchLogData(monopolyMarket.getWeekStateData().getSystemGroupId(),
                    monopolyMarket.getWeekStateData().getWeekId(), resGrab.getResGroupId(), playerId, resGrab.type, pointInfo.baseInfo.getPosIndex(), pointInfo.baseInfo.getUserId()));
        }else {
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_SEARCH_NO_MATCH_ANY);
            CrossAutoLogMgr.add(new NewMonopolyMarketSearchLogData(monopolyMarket.getWeekStateData().getSystemGroupId(),
                    monopolyMarket.getWeekStateData().getWeekId(), resGrab.getResGroupId(), playerId, resGrab.type, -1, -1));
        }
        return builder;
    }

    private NewMonopolyMarketResGrabPointInfo randomPointInfo(NewMonopolyMarketResGrab resGrab, List<Integer> poolList) {
        int index;
        if(poolList.size() == 0){
            return null;
        }
        Random random = new Random();
        if(poolList.size() == 1){
            index = poolList.get(0);
        }else {
            index = poolList.remove(random.nextInt(poolList.size()));
        }
        long now = DateHelper.getCurrentSecond();
        NewMonopolyMarketResGrabPointInfo result = null;
        NewMonopolyMarketResGrabPointInfo pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, index, true);
        if(skipSearch(now, pointInfo)){
            while (poolList.size() > 0){
                index = poolList.remove(random.nextInt(poolList.size()));
                pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, index, true);
                //资源可采及非保护时间
                if(skipSearch(now, pointInfo)){
                    continue;
                }
                result = pointInfo;
                break;
            }
        }else {
            result = pointInfo;
        }
        return result;
    }

    /**
     * 资源点是否可以被搜索到
     */
    private boolean skipSearch(long now, NewMonopolyMarketResGrabPointInfo pointInfo) {
        return pointInfo.baseInfo.getRemainTime() == 0 || pointInfo.baseInfo.getWaitTimeout() > now
                || (pointInfo.baseInfo.getSeatTime() > 0 && now - pointInfo.baseInfo.getSeatTime() <= GameConfig.NEWMONOPOLYMARKET_PROTECT_TIME);
    }

    /**
     * 获取玩家正在采集的据点
     *
     * @param serverId 发起查找的玩家区服
     * @param type
     * @param searchServerId  查找目标的玩家区服
     * @param id
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketResGrabGetUserPointRespMsg.Builder getUserPoint(long serverId, int type, int resType, long searchServerId, long id){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabGetUserPointRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabGetUserPointRespMsg.newBuilder();

        long targetUserId;
        UserBaseInfo targetUserInfo;
        if(type != 0){
            // 短编号查询
            Map<Long, CrossUserBaseInfo> map = CrossUserMgr.getUserAliasIdUserBaseInfoMap(searchServerId,false);
            if(map == null){
                builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_NO_FOUND_USER_BY_PARAM);
                return builder;
            }
            CrossUserBaseInfo crossUserBaseInfo = map.get(id);
            if(crossUserBaseInfo == null){
                builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_NO_FOUND_USER_BY_PARAM);
                return builder;
            }
            targetUserInfo = crossUserBaseInfo.getUserBaseInfo();
            targetUserId = crossUserBaseInfo.getUserId();
        }else {
            targetUserId = id;
            targetUserInfo = CrossUserMgr.getUserBaseInfo(targetUserId);
            if(targetUserInfo == null){
                builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_NO_FOUND_USER_BY_PARAM);
                return builder;
            }
        }
        synchronized (this) {
            List<NewMonopolyMarketResGrab> list = new ArrayList<>();

            for (Map.Entry<Integer, ResourceServerGroup> groupEntry : monopolyMarket.getWeekStateData().getInnerGroupList().entrySet()) {
                int groupId = groupEntry.getKey();
                ResourceServerGroup resourceServerGroup = groupEntry.getValue();
                //过滤不在同一资源分组的资源点
                if(resourceServerGroup.getServerList().size() > 0 && (!resourceServerGroup.getServerList().contains(searchServerId)
                        || !resourceServerGroup.getServerList().contains(serverId))){
                    continue;
                }
                if(resType > 0 && resourceServerGroup.getResType() != resType){
                    continue;
                }
                NewMonopolyMarketResGrab grab = getMarketResGrabMap().get(groupId);
                if(grab != null){
                    list.add(grab);
                }
            }

            for (NewMonopolyMarketResGrab resGrab : list){
                Set<NewMonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(targetUserId,false);
                if(set != null){
                    for (NewMonopolyMarketResGrabPointInfo item : set){
                        if(item.baseInfo.getUserId() != targetUserId){
                            continue;
                        }
                        builder.addUserPointList(builderMonopolyMarketResGrabUserPointEntity(item));
                    }
                }
                builder.setUserId(targetUserId);
                builder.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(targetUserInfo));
            }
        }
        if(builder.getUserPointListCount() == 0){
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_THIS_USER_NO_POINT);
        }else {
            builder.setRet(0);
        }
        return builder;
    }

    /**
     * 玩家待领取奖励
     * @param userId
     * @return
     */
    public List<NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg> receiveRewardList(long userId){
        List<NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg> settlementList = new ArrayList<>();
        List<NewMonopolyMarketResGrabFinishData> list = getMonopolyMarketResGrabFinishDataList(userId,false);
        if(list != null && list.size() > 0){
            List<NewMonopolyMarketResGrabFinishData> tempList = new ArrayList<>();
            synchronized (list) {
                tempList.addAll(list);
                list.clear();
            }
            // 1 清空 入库
            for (NewMonopolyMarketResGrabFinishData item : tempList){
                NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.Builder settlement = NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.newBuilder();
                settlement.setType(item.getType());
                settlement.setPosIndex(item.getPosIndex());
                settlement.setSide(item.getSide());
                settlement.setLevel(item.getLevel());
                settlement.setRobName(item.getRobName());
                settlement.setRewardTime(item.getRewardTime());
                settlement.setRewardNum(item.getRewardNum());
                settlement.setTotalRewardNum(item.getTotalRewardNum());
                settlement.addAllDispatchObjectId(StringUtils.stringToIntegerList(item.getObjectStr(),","));
                settlement.setBuffValues(item.getBuffValues());
                settlement.setResGroupId(item.getResGroupId());
                item.setIsReceive(true);
                settlementList.add(settlement.build());
            }
            // 入库
            synchronized (tempResGrabFinishList){
                tempResGrabFinishList.addAll(tempList);
            }
        }
        return settlementList;
    }

    public List<NewMonopolyMarketResGrabFinishData> getMonopolyMarketResGrabFinishDataList(long userId, boolean newIfNull) {
        List<NewMonopolyMarketResGrabFinishData> list = userResGrabFinishMap.get(userId);
        if (list == null && newIfNull) {
            synchronized (userResGrabFinishMap){
                if(!userResGrabFinishMap.containsKey(userId)){
                    list = new ArrayList<>();
                    userResGrabFinishMap.put(userId, list);
                }
            }
        }
        return list;
    }

    /**
     * 玩家离开所有资源点
     * @param userId 玩家
     */
    public void exitAllSeat(long userId) {
        for (NewMonopolyMarketResGrab resGrab : marketResGrabMap.values()) {
            int posIndex = resGrab.userInPointMap.getOrDefault(userId, 0);
            exitPoint(resGrab, posIndex, userId);
        }
    }

    /**
     * 玩家离开特定资源分组的资源点
     * @param resGroupId 资源分组id
     * @param posIndex 位置
     * @param userId 玩家
     */
    public void exitPoint(int resGroupId, int posIndex, long userId) {
        NewMonopolyMarketResGrab resGrab = marketResGrabMap.get(resGroupId);
        if(resGrab != null){
            exitPoint(resGrab, posIndex, userId);
        }
    }

    /**
     * 玩家离开特定资源分组的资源点
     * @param resGrab 资源分组
     * @param posIndex 位置
     * @param userId 玩家
     */
    public void exitPoint(NewMonopolyMarketResGrab resGrab, int posIndex, long userId) {
        synchronized (resGrab){
            NewMonopolyMarketResGrabPointInfo pointInfo = resGrab.pointsMap.get(posIndex);
            if(pointInfo != null){
                pointInfo.userSet.remove(userId);
                resGrab.userInPointMap.remove(userId);
            }
        }
    }

    /**
     * 进入资源资源争夺战 大厅
     */
    public NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabRespMsg.Builder enterResGrab(int resGroupId, List<NewMonopolyMarketProto.NewMonopolyMarketResGrabEnterParamEntity> pageParamList,
                                                                                            long serverId, long userId, boolean isGetNotice) {
        NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabRespMsg.newBuilder();

        NewMonopolyMarketResGrab resGrab = marketResGrabMap.get(resGroupId);
        if(resGrab == null){
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_TYPE_NO_ERROR);
            return builder;
        }
        List<NewMonopolyMarketResGrabPointInfo> list = new ArrayList<>();
        // 计算边长最多有多少页
        int n = (resGrab.map.side + GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2 - 1) / GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2;
        for (NewMonopolyMarketProto.NewMonopolyMarketResGrabEnterParamEntity pageParam : pageParamList) {
            int x = pageParam.getPage() % n ;
            int y = pageParam.getPage() / n ;
            int startX = x * GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2 ;
            int startY = y * GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2 ;
            for (int i = 0; i < GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2; i++) {
                for (int j = 0; j < GameConfig.NEWMONOPOLYMARKET_INITIAL_LOADNUM_2; j++) {
                    int index = NewMonopolyMarketCommonMgr.calIndex(startX + j, startY + i,resGrab.map.side);
                    if(!isEmpty(resGrab, index)){
                        NewMonopolyMarketResGrabPointInfo pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, index, true);
                        if(pointInfo != null){
                            if(pageParam.getTime() == 0 || pageParam.getTime() < pointInfo.baseInfo.getChangeTime()){
                                list.add(pointInfo);
                            }
                        }
                    }
                }
            }
        }

        int resType = resGrab.type;
        int totalOutSpeed = 0;
        for (Map.Entry<Integer, NewMonopolyMarketResGrab> grabEntry : marketResGrabMap.entrySet()) {
            if(resType != grabEntry.getValue().type){
                continue;
            }
            Set<NewMonopolyMarketResGrabPointInfo> pointInfos = grabEntry.getValue().getUserPointSet(userId, false);
            if(pointInfos != null) {
                for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfos) {
                    if (grabEntry.getValue().map != null) {
                        Integer lv = grabEntry.getValue().map.indexLevelMap.get(pointInfo.baseInfo.getPosIndex());
                        if (lv != null) {
                            NewMonopolyMarketResConfigData configData = CrossNewMonopolyMarketConfigMgr.getMonopolyMarketResConfigData(pointInfo.baseInfo.getType(), lv);
                            if(configData != null) {
                                int outSpeed = NewMonopolyMarketCommonMgr.calResRate(0, configData.rewardValue1, configData.rewardAdd1, configData.getId(), 1);
                                if(Config.isDebug()){
                                    CrossNewMonopolyMarketMgr.getLogger().info("outSpeed:{}", outSpeed);
                                }
                                totalOutSpeed += outSpeed;
                            }
                        }
                    }
                }
            }
        }
        builder.setAllOutSpeed(totalOutSpeed);

        for(NewMonopolyMarketResGrabPointInfo item : list){
            NewMonopolyMarketProto.NewMonopolyMarketResGrabPointEntity.Builder grabPointEntity = builderMonopolyMarketResGrabPointEntity(item);
            if(item.baseInfo.getUserId() > 0){
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.baseInfo.getUserId());
                if(userBaseInfo != null){
                    grabPointEntity.setServerId(userBaseInfo.getServerId());
                }
            }
            builder.addPointList(grabPointEntity);
        }
        if(isGetNotice){
            NewMonopolyMarketNoticeData noticeData = monopolyMarket.getNewMonopolyMarketNoticeData(resGrab.getResGroupId(), serverId);
            if(noticeData != null){
                builder.setNewNotice(monopolyMarket.builderMonopolyMarketNoticeEntity(noticeData));
            }
        }
        builder.setTime(DateHelper.getCurrentSecond());
        builder.setRet(0);
        for (NewMonopolyMarketProto.NewMonopolyMarketResGrabEnterParamEntity paramEntity : pageParamList) {
            builder.addPageList(paramEntity.getPage());
        }
        return builder;
    }
    /**
     * 进入资源资源争夺战 据点
     */
    public NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabPointRespMsg.Builder enterResGrabPoint(long userId,long serverId, int groupId, int posIndex) {
        NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabPointRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketEnterResGrabPointRespMsg.newBuilder();

        NewMonopolyMarketResGrab resGrab = marketResGrabMap.get(groupId);
        if(resGrab == null){
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_TYPE_NO_ERROR);
            return builder;
        }
        if(isEmpty(resGrab,posIndex)){
            builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_POINT_NO_EXIST);
            return builder;
        }
        NewMonopolyMarketResGrabPointInfo pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, posIndex,false);
        builder.setPointInfo(builderMonopolyMarketResGrabPointDetailEntity(pointInfo));
        pointInfo.userSet.add(userId);
        resGrab.userInPointMap.put(userId,posIndex);
        builder.setRet(0);
        return builder;
    }

    /**
     * 资源争夺战 占领据点
     * @param userId
     * @param serverId
     * @param ctsMsg client to server
     * @param userBaseInfo
     * @param objectInfoList 派遣信息
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketResGrabActionToGameServerMsg.Builder action(long userId, long serverId, NewMonopolyMarketProto.NewMonopolyMarketResGrabActionReqMsg ctsMsg,
                                                                                                      UserBaseInfo userBaseInfo, List<NewMonopolyMarketBaseBattleObjectInfo> objectInfoList, int buffAddTimes ){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabActionToGameServerMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabActionToGameServerMsg.newBuilder();
        builder.setActionType(ctsMsg.getActionType());
        builder.setType(ctsMsg.getType());
        builder.setResGroupId(ctsMsg.getResGroupId());
        builder.setPosIndex(ctsMsg.getPosIndex());

        //客户端消息
        NewMonopolyMarketProto.NewMonopolyMarketResGrabActionRespMsg.Builder stcMsg = NewMonopolyMarketProto.NewMonopolyMarketResGrabActionRespMsg.newBuilder();

        //资源分组验证
        ResourceServerGroup resourceServerGroup = monopolyMarket.getResourceServerGroup(ctsMsg.getResGroupId());
        if(resourceServerGroup == null || resourceServerGroup.getResType() != ctsMsg.getType()){
            stcMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            builder.setStcMsg(stcMsg);
            return builder;
        }
        //资源分组范围是否相同
        if(resourceServerGroup.getServerList().size() > 0 && !resourceServerGroup.getServerList().contains(serverId)){
            stcMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            builder.setStcMsg(stcMsg);
            return builder;
        }
        synchronized (this){
            //资源分组
            NewMonopolyMarketResGrab resGrab = getMarketResGrabMap().get(ctsMsg.getResGroupId());
            if(resGrab == null){
                stcMsg.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_TYPE_NO_ERROR);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            //地图信息校验
            if(resGrab.map == null){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_NO_MAP);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            if(resGrab.map.indexLevelList.size() <= ctsMsg.getPosIndex() ){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_POINT_NO_EXIST);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            Integer level = resGrab.map.indexLevelList.get(ctsMsg.getPosIndex());
            if(level == 0){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_POINT_NO_EXIST);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            //资源点配置
            NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(resGrab, ctsMsg.getPosIndex());
            if(configData == null){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_OFFICE_SEAT_CONFIG_NO_EXIST);
                builder.setStcMsg(stcMsg);
                return builder;
            }
            NewMonopolyMarketResGrabPointInfo pointInfo = getMonopolyMarketResGrabPointInfo(resGrab, ctsMsg.getPosIndex(),false);
            if(pointInfo == null){
                stcMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            // 加个保护 如果今天未重置据点 不让操作
            if(DateHelper.getDiffDayNum(pointInfo.baseInfo.getResetTime()) != 0){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_NO_REFRESH);
                builder.setStcMsg(stcMsg);
                return builder;
            }
            // 资源点状态校验
            if(pointInfo.baseInfo.getSeatTime() != ctsMsg.getSeatTime() || pointInfo.baseInfo.getUserId() != ctsMsg.getSeatUserId()){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_SEAT_INFO_CHANGE);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            int now = DateHelper.getCurrentSecond();
            if(pointInfo.baseInfo.getSeatTime() > 0 && now >= pointInfo.baseInfo.getEndTime()){
                stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_FINISH);
                builder.setStcMsg(stcMsg);
                return builder;
            }

            NewMonopolyMarketResGrabRobLogData robLogData = new NewMonopolyMarketResGrabRobLogData();
            robLogData.setWeekId(monopolyMarket.getWeekStateData().getWeekId());
            robLogData.setGroupId(monopolyMarket.getGroupId());
            robLogData.setResGroupId(resGrab.getResGroupId());
            robLogData.setActionType(ctsMsg.getActionType());
            switch (ctsMsg.getActionType()){
                case 2:
                case 0:{

                    //中间状态
                    if(pointInfo.baseInfo.getWaitTimeout() > 0 && now <= pointInfo.baseInfo.getWaitTimeout()){
                        stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_POINT_CHANGING);
                        builder.setStcMsg(stcMsg);
                        return builder;
                    }

                    // 不能重复入座
                    if(pointInfo.baseInfo.getUserId() == userId){
                        stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_NO_CAN_SEATED_REPEATED_POSITION);
                        builder.setStcMsg(stcMsg);
                        return builder;
                    }
                    // 多判断一次 怕跨服消息还没回给区服 立马再派遣一次
                    for (Map.Entry<Integer, NewMonopolyMarketResGrab> entry : getMarketResGrabMap().entrySet()) {
                        if(isRepeatDispatch(entry.getValue(), userId, objectInfoList)){
                            stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_OBJECT_ID_IS_DUPLICATE);
                            builder.setStcMsg(stcMsg);
                            return builder;
                        }
                    }
                    boolean isTeamLimit = isTeamLimit(userId, resGrab.type);
                    boolean success;
                    long defenderId = pointInfo.baseInfo.getUserId();
                    UserBaseInfo defenderInfo = CrossUserMgr.getUserBaseInfo(defenderId);

                    //防守，npc也有初始队伍及血量
                    List<NewMonopolyMarketBaseBattleObjectInfo> defendObjectList = pointInfo.baseInfo.getObjectInfoList();
                    //当前战力
                    long attackPower = calAttackValue(objectInfoList, 0);
                    if(Config.isDebug()) {
                        CrossNewMonopolyMarketMgr.getLogger().info("attackPower : {}", attackPower);
                    }
                    //战斗模拟（可打残血的目标）
                    battle(pointInfo, userId, objectInfoList, stcMsg, 0, configData, defendObjectList);
                    success = attackPower >= pointInfo.baseInfo.getBlood();
                    stcMsg.setDamage(success ? pointInfo.baseInfo.getBlood() : attackPower);
                    robLogData.setObjectStr(getObjectStr(defendObjectList));
                    robLogData.setValue(attackPower);
                    if(defenderId == 0) {
                        // 需要攻打 npc
                        robLogData.setUserId(0);
                        robLogData.setRemainTime(pointInfo.baseInfo.getRemainTime());
                        stcMsg.setPointStatus(0);
                    }else {
                        robLogData.setUserId(pointInfo.baseInfo.getUserId());
                        int rewardNum = 0;
                        int totalRewardTime = now - pointInfo.baseInfo.getSeatTime();
                        // 计算掠夺资源
                        if(success){
                            // 上次采集到结束的收益
                            rewardNum = calRewardNum(resourceServerGroup.getServerList().size(), pointInfo.baseInfo.getProduceRewardLastTime(),now, configData);
                            int rewardTime = now - pointInfo.baseInfo.getProduceRewardLastTime();
                            // 总采集的资源
                            int totalRewardNum = calRewardNum(resourceServerGroup.getServerList().size(), pointInfo.baseInfo.getSeatTime(),now, configData);

                            // 保存被抢记录并通知区服有奖励可领
                            saveFinishRecord(resGrab,pointInfo,configData,userBaseInfo.getNickName(),rewardNum,totalRewardNum,totalRewardTime,now,rewardTime,pointInfo.baseInfo.getProduceRewardLastTime());
                            // 离开位置
                            leavePointInfo(resGrab, pointInfo, now);
                            robLogData.setRewardNum(totalRewardNum);
                            robLogData.setRemainTime(pointInfo.baseInfo.getRemainTime());
                        }else {
                            robLogData.setRemainTime(pointInfo.baseInfo.getRemainTime() - totalRewardTime);
                        }
                        addResGrabReport(resGrab, userId, userBaseInfo, pointInfo.baseInfo.getPosIndex(), defenderInfo.getServerId(), defenderId, success, configData.getLevel(), rewardNum, ctsMsg.getActionType());
                        stcMsg.setPointStatus(1);
                    }
                    stcMsg.setIsSuccess(success);
                    List<String> robRewardList = StringUtils.stringToStringList(configData.getAttackReward(), "\\|");
                    int rewardNum;
                    if(success){
                        // 入座成功收益
                        List<Integer> rewardItemList = StringUtils.stringToIntegerList(robRewardList.get(1), "=");
                        rewardNum = rewardItemList.get(1);

                        if(!isTeamLimit) {
                            // 占领据点
                            occupyPoint(resGrab, serverId, userId, now, pointInfo, objectInfoList, 0);
                            CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo);

                            // 加公告
                            if(configData.getIsad() == 1){
                                // 队伍未满，直接占领
                                monopolyMarket.addNotice(resGrab.type, userId, defenderId, pointInfo.baseInfo.getPosIndex(), resGrab.getResGroupId(), ctsMsg.getActionType(), 1);
                            }
                        }else {
                            // 需要撤回一队
                            // 缓存当前派遣
                            CrossNewMonopolyMarketUserData userData = monopolyMarket.getNewMonopolyMarketUserData(serverId, userId, true);
                            userData.setObjectInfoList(objectInfoList);
                            // 先派遣npc
                            initNpcInfo(resGrab, pointInfo);
                            // 设置等待时限
                            pointInfo.baseInfo.setWaitTimeout(1 + GameConfig.NEWMONOPOLYMARKET_LEAVE_TIME + DateHelper.getCurrentSecond());

                            userData.setActionType(ctsMsg.getActionType());
                            synchronized (resGrab.updateAndAddPointInfoSet){
                                resGrab.updateAndAddPointInfoSet.add(pointInfo);
                            }

                            // 加公告
                            if(configData.getIsad() == 1 && defenderId > 0){
                                //队伍满了，打真人才有缓存
                                NewMonopolyMarketNoticeData noticeData = monopolyMarket.initNewMonopolyMarketNoticeData(resGrab.type, userId, defenderId, pointInfo.baseInfo.getPosIndex(), resGrab.getResGroupId(), ctsMsg.getActionType(), 0);
                                //缓存真人公告
                                pointInfo.noticeData = noticeData;

                                synchronized (resGrab.checkNoticeDataPointInfoSet){
                                    resGrab.checkNoticeDataPointInfoSet.add(pointInfo);
                                }
                            }

                            NewMonopolyMarketProto.NewMonopolyMarketResWaitDispatchPointTemp.Builder waitBuilder = NewMonopolyMarketProto.NewMonopolyMarketResWaitDispatchPointTemp.newBuilder();
                            waitBuilder.setPosIndex(pointInfo.baseInfo.getPosIndex());
                            waitBuilder.setResGroupId(pointInfo.baseInfo.getResGroupId());
                            waitBuilder.setTimeout(pointInfo.baseInfo.getWaitTimeout());
                            builder.setWait(waitBuilder);
                            stcMsg.setChangeTeam(true);
                        }

                    }else {
                        List<Integer> rewardItemList = StringUtils.stringToIntegerList(robRewardList.get(0), "=");
                        rewardNum = rewardItemList.get(1);

                        pointInfo.baseInfo.setBlood(pointInfo.baseInfo.getBlood() - attackPower);
                        //更新血量
                        equalSharesObjectBlood(pointInfo.baseInfo.getBlood(), pointInfo.baseInfo.getObjectInfoList());
                    }

                    //战斗奖励
                    addUserRankValue(userId, rewardNum);
                    stcMsg.setRewardNum(rewardNum);
                    builder.setRewardNum(rewardNum);
                    robLogData.setSitReward(rewardNum);

                    stcMsg.addAllObjectList(ctsMsg.getObjectIdList());
                    robLogData.setWin(success);
                    robLogData.setRobId(userId);
                    robLogData.setRobObjectStr(getObjectStr(objectInfoList));
                    robLogData.setRobValue(calPointValue(objectInfoList, 0));
                }
                break;
                case 1:{
                    // 撤回
                    if(pointInfo.baseInfo.getUserId() != userId){
                        stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_IS_NOT_CURRENTLY_IN_THIS_SEAT);
                        builder.setStcMsg(stcMsg);
                        return builder;
                    }
                    // 结算
                    robLogData.setUserId(pointInfo.baseInfo.getUserId());
                    robLogData.setObjectStr(getObjectStr(pointInfo.baseInfo.getObjectInfoList()));
                    robLogData.setValue(calPointValue(pointInfo.baseInfo.getObjectInfoList(), 0));
                    robLogData.setRemainTime(pointInfo.baseInfo.getRemainTime());

                    NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.Builder settlement = normalSettlement(resGrab, pointInfo,true, now);
                    builder.setSettlement(settlement);

                    stcMsg.setPointInfo(builderMonopolyMarketResGrabPointDetailEntity(pointInfo));
                    robLogData.setRewardNum(settlement.getRewardNum());
                    builder.setRewardNum(settlement.getRewardNum());
                }
                break;
                default:{
                    stcMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_TYPE_ERROR);
                    builder.setStcMsg(stcMsg);
                    return builder;
                }
            }
            broadcastMonopolyMarketResGrabRespMsg(pointInfo, userId);

            stcMsg.setPointInfo(builderMonopolyMarketResGrabPointDetailEntity(pointInfo));
            // 加日志
            robLogData.setGroupId(monopolyMarket.getWeekStateData().getSystemGroupId());
            robLogData.setPosIndex(ctsMsg.getPosIndex());
            robLogData.setSide(resGrab.map.side);
            robLogData.setLevel(configData.getLevel());
            robLogData.setType(configData.getType());
            robLogData.setOccupyStr(getCurUserPoint(resGrab,userId));

//            NewMonopolyMarketLogMgr.addMonopolyMarketResGrabRobLogData(robLogData);
            CrossAutoLogMgr.add(robLogData);
        }
        stcMsg.setRet(0);
        builder.setStcMsg(stcMsg);
        return builder;
    }

    public boolean isTeamLimit(long userId, int resType){
        int totalTeamNum = getUserTotalTeamNum(userId, resType);
        if(resType == eMonopolyMarketResType.RES_KING_NEW.getValue()){
            return totalTeamNum >= GameConfig.NEWMONOPOLYMARKET_ARMYLIMIT_2;
        }else {
            return totalTeamNum >= GameConfig.NEWMONOPOLYMARKET_ARMYLIMIT_3;
        }
    }

    public int getUserTotalTeamNum(long userId, int resType) {
        int totalTeamNum = 0;
        for (Map.Entry<Integer, NewMonopolyMarketResGrab> grabEntry : getMarketResGrabMap().entrySet()) {
            if(resType > 0 && grabEntry.getValue().type != resType){
                continue;
            }
            Set<NewMonopolyMarketResGrabPointInfo> set = grabEntry.getValue().getUserPointSet(userId, false);
            if(set != null){
                totalTeamNum += set.size();
            }
        }
        return totalTeamNum;
    }

    /**
     * 初始npc队伍
     * @param pointInfo 资源点
     */
    private boolean initNpcInfo(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo) {
        if(!monopolyMarket.isNpcBloodInit()){
            return false;
        }
        Integer level = resGrab.map.indexLevelList.get(pointInfo.baseInfo.getPosIndex());
        if(level == null){
            level = 1;
        }
        long blood = getNpcBlood(pointInfo.baseInfo.getResGroupId(), pointInfo.baseInfo.getType(), level);
        pointInfo.baseInfo.setObjectInfoList(randomNpcObjectList(blood,  level, 6, pointInfo.baseInfo.getType()));
        pointInfo.baseInfo.setTotalBlood(blood);
        pointInfo.baseInfo.setBlood(blood);
        return true;
    }

    /**
     * 初始npc队伍
     * @param blood 总血量
     * @param num 对象数量
     * @param level 资源等级
     * @param type 资源类型
     * @return
     */
    public List<NewMonopolyMarketBaseBattleObjectInfo> randomNpcObjectList(long blood, int level, int num, int type){
        List<NewMonopolyMarketBaseBattleObjectInfo> list = new ArrayList<>(num);

        //随机一批品质
        //权重
        List<Integer> weightList;
        if(type == eMonopolyMarketResType.RES_KING_NEW.getValue()){
            List<String> paramList = StringUtils.stringToStringList(GameConfig.NEWMONOPOLYMARKET_RESOURCE_NPC_PIC_1, "#");
            weightList = StringUtils.stringToIntegerList(paramList.get(level - 1), "\\|");
        }else {
            List<String> paramList = StringUtils.stringToStringList(GameConfig.NEWMONOPOLYMARKET_RESOURCE_NPC_PIC_2, "#");
            weightList = StringUtils.stringToIntegerList(paramList.get(level - 1), "\\|");
        }
        Random random = new Random();
        //品质，數量
        Map<Integer, Integer> qualityNumMap = new HashMap<>();
        for (int i = 0; i < num; i++) {
            int idx = RandomHelper.getRandomIndexByWeight(weightList, random);
            int n = qualityNumMap.getOrDefault(idx + 1, 0);
            qualityNumMap.put(idx + 1, n + 1);
        }
        List<Integer> objList = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : qualityNumMap.entrySet()) {
            objList.addAll(randomNpcObjectId(entry.getValue(), entry.getKey(), type));
        }
        for (int i = 0; i < num; i++) {
            NewMonopolyMarketBaseBattleObjectInfo info;
            if(type == eMonopolyMarketResType.RES_KING_NEW.getValue()){
                info = new NewMonopolyMarketPatronsInfo();
            }else {
                info = new NewMonopolyMarketBeautyInfo();
            }
            info.setId(objList.get(i));
            list.add(info);
        }
        equalSharesObjectBlood(blood, list);
        for (NewMonopolyMarketBaseBattleObjectInfo info : list) {
            info.setTotalBlood(info.getBlood());
            info.setBase(info.getBlood());
        }
        return list;
    }

    /**
     * 随机num个形象
     * @param num 数量
     * @param quality 品质
     * @param type
     * @return
     */
    public List<Integer> randomNpcObjectId(int num, int quality, int type){
        //待选
        List<Integer> poolList = new ArrayList<>();
        //备选
        List<Integer> secondList = new ArrayList<>();
        if(type == eMonopolyMarketResType.RES_KING_NEW.getValue()){
            List<Integer> configList = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_NPC_PARTON, ";");
            for (Integer id : configList) {
                PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(id);
                if(patronsInfo == null){
                    continue;
                }
                if(patronsInfo.getQuality() == quality){
                    poolList.add(patronsInfo.getId());
                }else {
                    secondList.add(patronsInfo.getId());
                }
            }
        }else {
            List<Integer> configList = StringUtils.stringToIntegerList(GameConfig.NEWMONOPOLYMARKET_NPC_BEAUTY, ";");
            for (Integer id : configList) {
                BeautyInfo beautyInfo = BeautyMgr.getBeautyInfo(id);
                if(beautyInfo == null){
                    continue;
                }
                if(beautyInfo.getQuality() == quality){
                    poolList.add(beautyInfo.getBeautyId());
                }else {
                    secondList.add(beautyInfo.getBeautyId());
                }
            }
        }
        if(poolList.size() + secondList.size() < num){

        }
        Random random = new Random();
        List<Integer> result = new ArrayList<>(num);
        while (result.size() < num && poolList.size() > 0){
            result.add(poolList.remove(random.nextInt(poolList.size())));
        }
        while (result.size() < num && secondList.size() > 0){
            result.add(secondList.remove(random.nextInt(secondList.size())));
        }
        return result;
    }

    /**
     * 平摊剩余血量
     * @param blood 血量
     * @param objectInfoList  队伍
     */
    public void equalSharesObjectBlood(long blood, List<NewMonopolyMarketBaseBattleObjectInfo> objectInfoList){
        int size = objectInfoList.size();
        long perBlood = blood / size;
        long moreBlood = blood % size;
        for (int i = 0; i < size; i++) {
            NewMonopolyMarketBaseBattleObjectInfo obj = objectInfoList.get(i);
            if(i == size - 1){
                obj.setBlood(perBlood + moreBlood);
            }else {
                obj.setBlood(perBlood);
            }
        }
    }

    /**
     * 占领据点
     * @return
     */
    public void occupyPoint(NewMonopolyMarketResGrab resGrab, long serverId, long userId, int now, NewMonopolyMarketResGrabPointInfo pointInfo,
                            List<NewMonopolyMarketBaseBattleObjectInfo> objectInfoList, int buffValues){
        // 对象派遣
        pointInfo.baseInfo.setUserId(userId);
        pointInfo.baseInfo.setSeatTime(now);
        pointInfo.baseInfo.setReceiveLastTime(now);
        pointInfo.baseInfo.setProduceRewardLastTime(now);
        pointInfo.baseInfo.setRemainTime(calResTotalTime(resGrab, pointInfo.baseInfo.getPosIndex()));
        pointInfo.baseInfo.setEndTime(now + pointInfo.baseInfo.getRemainTime());

        pointInfo.baseInfo.getObjectInfoList().clear();
        pointInfo.objectInfoMap.clear();
        pointInfo.baseInfo.setWaitTimeout(0);

        for (NewMonopolyMarketBaseBattleObjectInfo info : objectInfoList) {
            info.setBlood(info.getBase());
        }
        pointInfo.baseInfo.setServerId(serverId);
        pointInfo.baseInfo.getObjectInfoList().addAll(objectInfoList);
        pointInfo.baseInfo.setTotalBlood(calPointValue(objectInfoList, buffValues));
        pointInfo.baseInfo.setBlood(pointInfo.baseInfo.getTotalBlood());
        for (NewMonopolyMarketBaseBattleObjectInfo item : objectInfoList){
            pointInfo.objectInfoMap.put(item.getId(),item);
        }
        pointInfo.baseInfo.setChangeTime(now);
        addCurPointInfo(resGrab,pointInfo);
        synchronized (resGrab.updateAndAddPointInfoSet){
            resGrab.updateAndAddPointInfoSet.add(pointInfo);
        }
    }

    private void addCurPointInfo(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo){
        resGrab.getUserPointSet(pointInfo.baseInfo.getUserId(),true).add(pointInfo);
        setMinResGrabEndTime(resGrab,pointInfo);
        resGrab.collectingPointInfoList.add(pointInfo);
    }

    public void setMinResGrabEndTime(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo){
        int endTime = getPointEndTime(resGrab, pointInfo);
        if(endTime != -1 && (resGrab.minResGrabEndTime == 0 || endTime < resGrab.minResGrabEndTime)){
            resGrab.minResGrabEndTime = endTime;
            CrossNewMonopolyMarketMgr.getLogger().info("下次执行榷场资源定时任务时间为：{},delay:{},groupId:{}",resGrab.minResGrabEndTime,resGrab.minResGrabEndTime - DateHelper.getCurrentSecond(),pointInfo.baseInfo.getGroupId());
        }
    }

    /**
     * 计算资源点结算的时间  -1表示不能结算
     */
    public int getPointEndTime(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo item){
        if(item.baseInfo.getUserId() > 0){
            int endTime = calDailyEndTime(resGrab.type, item.baseInfo.getSeatTime());
            return Math.min(endTime, item.baseInfo.getEndTime());
        }
        return -1;
    }

    /**
     * 计算当前时间的资源点 当天结算时间
     * @param type 资源类型
     * @param seatTime 资源点占位时间
     * @return
     */
    private int calDailyEndTime(int type,int seatTime){
        // 当前结算时间
        int todayStartTime = DateHelper.getZeroTime(seatTime);
        if(eMonopolyMarketResType.RES_KING_NEW.getValue() == type){
            return todayStartTime + ConfigMgr.getKingDailyEndTimeNew();
        }else if(eMonopolyMarketResType.RES_QUEEN_NEW.getValue() == type){
            return todayStartTime + ConfigMgr.getQueenDailyEndTimeNew();
        }
        return 0;
    }

    /**
     * 通知区服加战报
     * @param resGrab
     * @param attackerId
     * @param attackerInfo
     * @param posIndex
     * @param defenderServerId
     * @param defenderId
     * @param isWin
     */
    private void addResGrabReport(NewMonopolyMarketResGrab resGrab, long attackerId, UserBaseInfo attackerInfo, int posIndex, long defenderServerId,
                                  long defenderId, boolean isWin, int level, int addRankValue, int robType){
        NewMonopolyMarketProto.NewMonopolyMarketSynAttackToGameServerMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketSynAttackToGameServerMsg.newBuilder();
        builder.setType(resGrab.type);
        builder.setRobedId(defenderId);
        builder.setPosIndex(posIndex);
        builder.setAttackId(attackerId);
        if(attackerInfo.getServerId() != defenderServerId){
            builder.setAttackInfo(PlayerBasePb.parsePlayerBaseTempMsg(attackerInfo));
        }
        builder.setSystemGroupId(monopolyMarket.getWeekStateData().getSystemGroupId());
        builder.setWeekId(monopolyMarket.getWeekStateData().getWeekId());
        builder.setResGroupId(resGrab.getResGroupId());
        builder.setIsWin(isWin);
        builder.setLevel(level);
        builder.setX(posIndex % resGrab.map.side + 1);
        builder.setY(posIndex / resGrab.map.side + 1);
        builder.setAddValue(addRankValue);
        builder.setResGroupId(resGrab.getResGroupId());
        builder.setRobType(robType);
        MessageHelper.sendPacket(defenderServerId,defenderId, YanQuMessageUtils.buildMessage(GameProtocol.S_NEW_MONOPOLY_MARKET_SYN_ATTACK, builder));
    }

    /**
     * 撤回据点
     */
    private void leavePointInfo(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo, int endTime){
        Set<NewMonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(pointInfo.baseInfo.getUserId(),true);
        set.remove(pointInfo);
        resGrab.collectingPointInfoList.remove(pointInfo);
        // 收益时间(每次占领后都是满格采集时间，不会枯竭)
//        int time = endTime - pointInfo.baseInfo.getSeatTime();
//        pointInfo.baseInfo.setRemainTime(pointInfo.baseInfo.getRemainTime() - time);
        pointInfo.baseInfo.setRemainTime(calResTotalTime(resGrab, pointInfo.baseInfo.getPosIndex()));
        pointInfo.baseInfo.setUserId(0);
        pointInfo.baseInfo.setSeatTime(0);
        pointInfo.baseInfo.setProduceRewardLastTime(0);
        pointInfo.baseInfo.setReceiveLastTime(0);
        pointInfo.baseInfo.setObjectInfoList(new ArrayList<>());
        pointInfo.objectInfoMap.clear();
        pointInfo.baseInfo.setServerId(0);
        //设置npc
        initNpcInfo(resGrab, pointInfo);

        pointInfo.baseInfo.setChangeTime(endTime);
        synchronized (resGrab.updateAndAddPointInfoSet){
            resGrab.updateAndAddPointInfoSet.add(pointInfo);
        }
    }

    /**
     * 抢夺成功后结算
     * @param resGrab
     * @param pointInfo
     * @param configData
     * @param robName
     * @param rewardNum
     * @param totalRewardNum
     * @param totalRewardTime
     * @param endTime
     * @param totalCalTime 该记录总采集时长
     * @param startCalTime 该记录开始计算的时间
     */
    private void saveFinishRecord(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo, NewMonopolyMarketResConfigData configData,
                                  String robName, int rewardNum, int totalRewardNum, int totalRewardTime, int endTime, int totalCalTime, int startCalTime){
        // 被动结算 保存记录 通知区服有结算
        NewMonopolyMarketResGrabFinishData finishData = new NewMonopolyMarketResGrabFinishData();
        finishData.setId(CrossNewMonopolyMarketMgr.maxResGrabFinishId.incrementAndGet());
        finishData.setType(pointInfo.baseInfo.getType());
        finishData.setUserId(pointInfo.baseInfo.getUserId());
        finishData.setPosIndex(pointInfo.baseInfo.getPosIndex());
        finishData.setSide(resGrab.map.side);
        finishData.setLevel((byte)(configData.getLevel()));
        finishData.setRobName(robName);
        finishData.setObjectStr(getObjectStr(pointInfo.baseInfo.getObjectInfoList()));
        finishData.setRewardTime(totalRewardTime);
        finishData.setRewardNum(rewardNum);
        finishData.setTotalRewardNum(totalRewardNum);
        finishData.setTotalTime(totalCalTime);
        finishData.setStartTime(startCalTime);
        finishData.setWeekId(monopolyMarket.getWeekStateData().getWeekId());
        finishData.setGroupId(monopolyMarket.getWeekStateData().getSystemGroupId());
        finishData.setResGroupId(resGrab.getResGroupId());
        finishData.setTime(endTime);
        finishData.setInsertOption();
        //暂时，还没有活动冲榜
        finishData.setIsJoinRank(true);
        if(finishData.getRewardNum() > 0){
            synchronized (userResGrabRankMap){
                userResGrabRankMap.put(finishData.getId(),finishData);
            }
            addUserRankValue(finishData.getUserId(), finishData.getRewardNum());
        }else {
            finishData.setIsJoinRank(true);
        }
        List<NewMonopolyMarketResGrabFinishData> list = getMonopolyMarketResGrabFinishDataList(pointInfo.baseInfo.getUserId(),true);
        synchronized (list){
            list.add(finishData);
        }
        synchronized (tempResGrabFinishList) {
            tempResGrabFinishList.add(finishData);
        }
    }

    private void addUserRankValue(long userId, int rewardNum) {
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if(userBaseInfo == null){
            return;
        }
        if(rewardNum <= 0){
            return;
        }
        CrossNewMonopolyMarketUserData userData = monopolyMarket.getNewMonopolyMarketUserData(userBaseInfo.getServerId(), userId, true);
        userData.setResGetNum(rewardNum + userData.getResGetNum());
        userData.setLastUpdate(DateHelper.getCurrentSecond());
        monopolyMarket.changeUserRank(userData);

        monopolyMarket.addUserDataUpdate(userData);
    }

    /**
     * 正常采集据点结算  不包括抢夺
     * @param pointInfo
     */
    private NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.Builder normalSettlement(NewMonopolyMarketResGrab resGrab, NewMonopolyMarketResGrabPointInfo pointInfo, boolean recall, int endTime){
        NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(resGrab, pointInfo.baseInfo.getPosIndex());
        NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.Builder settlementMsg = null;
        ResourceServerGroup serverGroup = monopolyMarket.getWeekStateData().getInnerGroupList().get(resGrab.getResGroupId());
        // 上次采集到结束的收益
        int rewardNum = calRewardNum(serverGroup.getServerList().size(), pointInfo.baseInfo.getProduceRewardLastTime(), endTime, configData);
        int rewardTime = endTime - pointInfo.baseInfo.getProduceRewardLastTime();
        // 总采集的资源
        int totalRewardTime = endTime - pointInfo.baseInfo.getSeatTime();
        int totalRewardNum = calRewardNum(serverGroup.getServerList().size(), pointInfo.baseInfo.getSeatTime(),endTime,configData);
        if(recall){
            // 玩家撤回主动推给区服结算
            settlementMsg = NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.newBuilder();
            settlementMsg.setType(resGrab.type);
            settlementMsg.setPosIndex(pointInfo.baseInfo.getPosIndex());
            settlementMsg.setSide(resGrab.map.side);
            settlementMsg.setLevel(configData.getLevel());
            settlementMsg.setRewardTime(totalRewardTime);
            settlementMsg.setRewardNum(rewardNum);
            settlementMsg.addAllDispatchObjectId(pointInfo.objectInfoMap.keySet());
            settlementMsg.setTotalRewardNum(totalRewardNum);
            settlementMsg.setResGroupId(resGrab.getResGroupId());

            addUserRankValue(pointInfo.baseInfo.getUserId(), rewardNum);
        }else {
            saveFinishRecord(resGrab,pointInfo,configData,"", rewardNum, totalRewardNum, totalRewardTime, endTime, rewardTime, pointInfo.baseInfo.getProduceRewardLastTime());
        }
        // 离开位置
        leavePointInfo(resGrab,pointInfo,endTime);
        return settlementMsg;
    }

    /**
     * 采集收益计算
     * @param startTime
     * @param endTime
     * @param configData
     * @return
     */
    public int calRewardNum(int serverNum, int startTime, int endTime, NewMonopolyMarketResConfigData configData){
        int rewardTime = endTime - startTime;
        // 采集单位数量
        int i = calResProduceTime(configData.getType(), rewardTime);
        // 总采集的资源
        int rewardNum = i * NewMonopolyMarketCommonMgr.calResRate(serverNum, configData.rewardValue1, configData.rewardAdd1,configData.getId(), 1);
        return Math.max(rewardNum, 0);
    }

    private int calResProduceTime(int type ,int time){
        int cd = NewMonopolyMarketCommonMgr.getResGrabPointCD(type);
        return time / cd;
    }

    /**
     * 计算总血量
     * @param objectInfos
     * @param buffValues
     * @return
     */
    private static long calPointValue(List<NewMonopolyMarketBaseBattleObjectInfo> objectInfos,int buffValues){
        long value = 0;
        for(NewMonopolyMarketBaseBattleObjectInfo objectInfo : objectInfos){
            value += calAttackValue(objectInfo, buffValues);
        }
        return value;
    }

    /**
     * 计算总战斗力
     * @param objectInfos
     * @param buffValues
     * @return
     */
    private static long calAttackValue(List<NewMonopolyMarketBaseBattleObjectInfo> objectInfos, int buffValues){
        long value = 0;
        for(NewMonopolyMarketBaseBattleObjectInfo objectInfo : objectInfos){
            value += calAttackValue(objectInfo, buffValues);
        }
        return value;
    }

    /**
     * 计算派遣对象的战斗力
     * @param objectInfo 派遣对象
     * @param buffValue buff 加成
     * @return
     */
    private static long calAttackValue(NewMonopolyMarketBaseBattleObjectInfo objectInfo, int buffValue){
        return BigDecimal.valueOf(objectInfo.getBase()).multiply(BigDecimal.valueOf(1000 + buffValue + objectInfo.getAddition())).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
    }

    /**
     * 计算派遣对象的血量
     * @param objectInfo 派遣对象
     * @param buffValue buff 加成
     * @return
     */
    private static long calBloodValue(NewMonopolyMarketBaseBattleObjectInfo objectInfo, int buffValue){
        return BigDecimal.valueOf(objectInfo.getBlood()).multiply(BigDecimal.valueOf(1000 + buffValue)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
    }

    private void broadcastMonopolyMarketResGrabRespMsg(NewMonopolyMarketResGrabPointInfo pointInfo, long excludeId ){
        NewMonopolyMarketProto.NewBroadcastMonopolyMarketRespMsg.Builder builder = NewMonopolyMarketProto.NewBroadcastMonopolyMarketRespMsg.newBuilder();
        builder.setType(3);
        NewMonopolyMarketProto.NewMonopolyMarketResGrabPointDetailBroadcastEntity.Builder detailBroadcast = NewMonopolyMarketProto.NewMonopolyMarketResGrabPointDetailBroadcastEntity.newBuilder();
        detailBroadcast.setType(pointInfo.baseInfo.getType());
        detailBroadcast.setPointEntity(builderMonopolyMarketResGrabPointDetailEntity(pointInfo));
        builder.setPointInfo(detailBroadcast);

        for(long userId : pointInfo.userSet){
            if(userId != excludeId){
                MessageHelper.sendPacket(CrossUserMgr.getServerIdByUserId(userId), userId, YanQuMessageUtils.buildMessage(ClientProtocol.U_NEW_MONOPOLY_MARKET_BROADCAST, builder));
            }
        }
    }

    /**
     * 获取玩家已有的据点
     * @return
     */
    private static String getCurUserPoint(NewMonopolyMarketResGrab resGrab, long userId){
        Set<NewMonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(userId,false);
        if(set != null){
            StringBuilder sb = new StringBuilder();
            for (NewMonopolyMarketResGrabPointInfo item : set){
                if(item.baseInfo.getUserId() != userId){
                    continue;
                }
                sb.append(item.baseInfo.getPosIndex()).append(",");
            }
            if(sb.length() > 0){
                return sb.substring(0,sb.length()-1);
            }
        }
        return "";
    }

    /**
     * 拼接派遣对象的id
     * @param objectInfoList
     * @return
     */
    private static String getObjectStr(List<NewMonopolyMarketBaseBattleObjectInfo> objectInfoList){
        StringBuilder sb = new StringBuilder();
        for (NewMonopolyMarketBaseBattleObjectInfo objectInfo : objectInfoList){
            sb.append(objectInfo.getId()).append(",");
        }
        if(sb.length() > 0){
            return sb.substring(0,sb.length()-1);
        }
        return "";
    }

    /**
     * @param pointInfo
     * @param attackObjectList
     * @return
     */
    private boolean battle(NewMonopolyMarketResGrabPointInfo pointInfo, long attackerId, List<NewMonopolyMarketBaseBattleObjectInfo> attackObjectList,
                           NewMonopolyMarketProto.NewMonopolyMarketResGrabActionRespMsg.Builder msg, int attackBuffValues,
                           NewMonopolyMarketResConfigData configData, List<NewMonopolyMarketBaseBattleObjectInfo> defendObjectList){
        //战斗动画优化，去掉0血的门客
        List<NewMonopolyMarketBaseBattleObjectInfo> copyDefendObjectList = new ArrayList<>();
        for (NewMonopolyMarketBaseBattleObjectInfo info : defendObjectList) {
            if(info.getBlood() > 0){
                copyDefendObjectList.add(info);
            }
        }
        BattleResult battleResult = battle(pointInfo.baseInfo.getUserId(), copyDefendObjectList, 0, attackerId, attackObjectList, attackBuffValues);
        //战斗详细信息
        msg.setBattleDetailList(BattlePb.parseBattleDetailListMsg(battleResult.getPatronsBattleDetailList()));
        //对手出战门客、座骑
        if(pointInfo.baseInfo.getType() == eMonopolyMarketResType.RES_KING_NEW.getValue()){
            // 门客
            for (NewMonopolyMarketBaseBattleObjectInfo item : copyDefendObjectList) {
                //
                msg.addEnemyPatronsList(monopolyMarket.builderMonopolyMarketPatronsEntity((NewMonopolyMarketPatronsInfo)item));
            }
        }else if(pointInfo.baseInfo.getType() == eMonopolyMarketResType.RES_QUEEN_NEW.getValue()){
            for (NewMonopolyMarketBaseBattleObjectInfo item : copyDefendObjectList) {
                //
                msg.addEnemyBeautyList(monopolyMarket.builderMonopolyMarketBeautyEntity((NewMonopolyMarketBeautyInfo)item));
            }
        }
        return battleResult.getWinUserId() == attackerId;
    }

    /**
     * 战斗 战斗力一样算 防守方胜利
     */
    public static BattleResult battle(long defenderId, List<NewMonopolyMarketBaseBattleObjectInfo> defendObjectList, int defendBuffValue,
                                      long attackerId, List<NewMonopolyMarketBaseBattleObjectInfo> attackObjectList, int attackBuffValue) {
        BattleResult battleResult = new BattleResult();
        int defendIndex = 0;
        int attackIndex = 0;
        NewMonopolyMarketBaseBattleObjectInfo defendObject = null;
        NewMonopolyMarketBaseBattleObjectInfo attackObject = null;
        long defendTotalBlood = 0;
        long attackTotalBlood = 0;

        long defendRemainBlood = 0;
        long attackRemainBlood = 0;
        while (true) {
            PatronsBattleDetail patronsBattleDetail;
            if(defendObject == null && defendObjectList.size() - 1 >= defendIndex){
                defendObject = defendObjectList.get(defendIndex);
                defendTotalBlood = defendRemainBlood = calAttackValue(defendObject, defendBuffValue);
            }
            if(attackObject == null && attackObjectList.size() - 1 >= attackIndex){
                attackObject = attackObjectList.get(attackIndex);
                attackTotalBlood = attackRemainBlood = calAttackValue(attackObject, attackBuffValue);
            }
            if(attackObject == null){
                battleResult.setWinUserId(defenderId);
                break;
            }
            if(defendObject == null){
                battleResult.setWinUserId(attackerId);
                break;
            }
            patronsBattleDetail = patronsBattle(defendObject,defendRemainBlood,defendTotalBlood, attackObject,attackRemainBlood,attackTotalBlood);

            battleResult.getPatronsBattleDetailList().add(patronsBattleDetail);
            defendRemainBlood = patronsBattleDetail.getEnemyPatronsCurrentBlood().longValue();
            attackRemainBlood = patronsBattleDetail.getMyPatronsCurrentBlood().longValue();
            if (defendRemainBlood <= 0) {
                defendIndex++;
                defendObject = null;
            }
            if (attackRemainBlood <= 0) {
                attackIndex++;
                attackObject = null;
            }
        }
        battleResult.setKillPatronsCount(defendIndex);

        return battleResult;
    }

    /**
     * 撤回队伍派遣到新资源点
     * @param userId 玩家
     * @param action 撤回或者派遣
     * @param resGroupId 撤回队伍
     * @param posIndex 撤回队伍
     * @param targetResGroupId  新资源点
     * @param targetPosIndex 新资源点
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketCrossResGrabChangeTeamConfirmRespMsg.Builder changeTeam(
            long serverId, long userId, int action, int resGroupId, int posIndex, int targetResGroupId, int targetPosIndex) {

        NewMonopolyMarketProto.NewMonopolyMarketCrossResGrabChangeTeamConfirmRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketCrossResGrabChangeTeamConfirmRespMsg.newBuilder();
        builder.setAction(action);
        NewMonopolyMarketProto.NewMonopolyMarketResGrabChangeTeamConfirmRespMsg.Builder clientMsg = NewMonopolyMarketProto.NewMonopolyMarketResGrabChangeTeamConfirmRespMsg.newBuilder();
        clientMsg.setResGroupId(targetResGroupId);
        synchronized (this){

            //新资源点
            NewMonopolyMarketResGrab targetMarketResGrab = getNewMonopolyMarketResGrab(targetResGroupId);
            if(targetMarketResGrab == null || targetMarketResGrab.pointsMap.get(targetPosIndex) == null){
                clientMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                builder.setStcMsg(clientMsg);
                return builder;
            }
            int now = DateHelper.getCurrentSecond();
            NewMonopolyMarketResGrabPointInfo targetPointInfo = targetMarketResGrab.pointsMap.get(targetPosIndex);
            if(action == 0){
                if(targetPointInfo.baseInfo.getUserId() == 0 && now <= targetPointInfo.baseInfo.getWaitTimeout()){
                    targetPointInfo.baseInfo.setWaitTimeout(0);
                }
                clientMsg.setRet(0);
                builder.setStcMsg(clientMsg);
                broadcastMonopolyMarketResGrabRespMsg(targetPointInfo, userId);

                NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(targetMarketResGrab, targetPosIndex);
                if(configData != null && configData.getIsad() == 1) {
                    if (targetPointInfo.noticeData != null) {
                        monopolyMarket.addNotice(targetPointInfo.noticeData);
                        targetPointInfo.noticeData = null;
                    }
                }

                return builder;
            }

            if(targetPointInfo.baseInfo.getWaitTimeout() == 0){
                clientMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_WAIT_CHANGE_TEAM_INFO_TIMEOUT);
                builder.setStcMsg(clientMsg);
                return builder;
            }
            if(targetPointInfo.baseInfo.getUserId() != 0 || targetPointInfo.baseInfo.getBlood() != targetPointInfo.baseInfo.getTotalBlood()
                || now > targetPointInfo.baseInfo.getWaitTimeout()){
                clientMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_WAIT_CHANGE_TEAM_INFO_TIMEOUT);
                builder.setStcMsg(clientMsg);
                return builder;
            }

            //队伍所在资源点
            NewMonopolyMarketResGrab marketResGrab = getNewMonopolyMarketResGrab(resGroupId);
            if(marketResGrab == null || marketResGrab.pointsMap.get(posIndex) == null){
                clientMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                builder.setStcMsg(clientMsg);
                return builder;
            }


            NewMonopolyMarketResGrabPointInfo backPointInfo = marketResGrab.pointsMap.get(posIndex);
            //撤回资源点结算
            if(backPointInfo.baseInfo.getUserId() != userId){
                //撤回的据点被抢了
                clientMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_RES_GRAB_IS_NOT_CURRENTLY_IN_THIS_SEAT);
                builder.setStcMsg(clientMsg);
                return builder;
            }

            CrossNewMonopolyMarketUserData userData = monopolyMarket.getNewMonopolyMarketUserData(serverId, userId, false);
            if(userData == null || userData.getObjectInfoList() == null){
                //没有队伍且玩家没有战斗胜利过
                clientMsg.setRet(GameErrorCode.E_ERROR_DATA);
                builder.setStcMsg(clientMsg);
                return builder;
            }

            //资源点配置
            NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(targetMarketResGrab, targetPosIndex);
            if(configData == null){
                clientMsg.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_OFFICE_SEAT_CONFIG_NO_EXIST);
                builder.setStcMsg(clientMsg);
                return builder;
            }

            //结算
            NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg.Builder settlement = normalSettlement(marketResGrab, backPointInfo, true, now);
            clientMsg.setSettlement(settlement);

            //队伍
            List<NewMonopolyMarketBaseBattleObjectInfo> objectInfoList = userData.getObjectInfoList();
            userData.setObjectInfoList(null);

            //占位
            occupyPoint(targetMarketResGrab, serverId, userId, now, targetPointInfo, objectInfoList, 0);

            for (NewMonopolyMarketBaseBattleObjectInfo info : objectInfoList) {
                clientMsg.addDispatchObjectId(info.getId());
            }

            broadcastMonopolyMarketResGrabRespMsg(targetPointInfo, userId);
            clientMsg.setPointInfo(builderMonopolyMarketResGrabPointDetailEntity(targetPointInfo));

            if(configData.getIsad() == 1){
                if(targetPointInfo.noticeData != null){
                    targetPointInfo.noticeData.setOccupyType(1);
                    monopolyMarket.addNotice(targetPointInfo.noticeData);
                    targetPointInfo.noticeData = null;
                }else {
                    // 加公告，驱逐npc
                    monopolyMarket.addNotice(targetMarketResGrab.type, userId, 0, targetPointInfo.baseInfo.getPosIndex(), targetMarketResGrab.getResGroupId(), userData.getActionType(), 1);
                }
            }
        }
        clientMsg.setRet(0);
        builder.setStcMsg(clientMsg);
        return builder;
    }


    public static PatronsBattleDetail patronsBattle(NewMonopolyMarketBaseBattleObjectInfo defender, long defendRemainBlood, long defendTotalBlood, NewMonopolyMarketBaseBattleObjectInfo attacker, long attackRemainBlood, long attackTotalBlood) {
        PatronsBattleDetail battleDetail = new PatronsBattleDetail();

        long oldAttackRemainBlood = attackRemainBlood;
        long oldDefendRemainBlood = defendRemainBlood;

        attackRemainBlood = oldAttackRemainBlood - oldDefendRemainBlood;
        defendRemainBlood = oldDefendRemainBlood - oldAttackRemainBlood;

        battleDetail.setEnemyPatronsId(defender.getId());
        battleDetail.setEnemyPatronsCurrentBlood(BigInteger.valueOf(defendRemainBlood));
        battleDetail.setEnemyPatronsTotalBlood(BigInteger.valueOf(defendTotalBlood));

        battleDetail.setMyPatronsId(attacker.getId());
        battleDetail.setMyPatronsCurrentBlood(BigInteger.valueOf(attackRemainBlood));
        battleDetail.setMyPatronsTotalBlood(BigInteger.valueOf(attackTotalBlood));

        return battleDetail;
    }

    /**
     * 是否重复派遣
     * @return
     */
    private boolean isRepeatDispatch(NewMonopolyMarketResGrab resGrab, long userId, List<NewMonopolyMarketBaseBattleObjectInfo> list){
        Set<NewMonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(userId,false);
        if(set == null){
            return false;
        }
        for (NewMonopolyMarketResGrabPointInfo item : set){
            if(item.baseInfo.getUserId() != userId){
                continue;
            }
            for (NewMonopolyMarketBaseBattleObjectInfo info : list){
                if(item.objectInfoMap.containsKey(info.getId())){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是否是空据点
     * @return
     */
    public static boolean isEmpty(NewMonopolyMarketResGrab resGrab, int posIndex){
        if(resGrab.map.indexLevelList.size() <= posIndex ){
            return true;
        }
        Integer level = resGrab.map.indexLevelList.get(posIndex);
        if(level == null){
            return true;
        }
        if(level == 0){
            return true;
        }
        return false;
    }

    public NewMonopolyMarketResGrabPointInfo getMonopolyMarketResGrabPointInfo(NewMonopolyMarketResGrab resGrab, int posIndex, boolean newIfNull){
        NewMonopolyMarketResGrabPointInfo pointInfo = resGrab.pointsMap.get(posIndex);
        if(pointInfo == null && newIfNull){
            synchronized (this) {
                pointInfo = resGrab.pointsMap.get(posIndex);
                if(pointInfo == null) {
                    NewMonopolyMarketResGrabPointData pointData = new NewMonopolyMarketResGrabPointData();
                    pointData.setWeekId(monopolyMarket.getWeekStateData().getWeekId());
                    pointData.setInsertOption();
                    pointData.setGroupId(monopolyMarket.getGroupId());
                    pointData.setResGroupId(resGrab.getResGroupId());
                    pointData.setType((byte) resGrab.type);
                    pointData.setPosIndex(posIndex);
                    pointData.setRemainTime(calResTotalTime(resGrab, posIndex));
                    pointData.setChangeTime(DateHelper.getCurrentSecond());
                    pointData.setResetTime(DateHelper.getTodayZeroTime());
                    pointInfo = new NewMonopolyMarketResGrabPointInfo(pointData);
                    initNpcInfo(resGrab, pointInfo);
                    resGrab.pointsMap.put(posIndex, pointInfo);
                }
            }
            synchronized (resGrab.updateAndAddPointInfoSet){
                resGrab.updateAndAddPointInfoSet.add(pointInfo);
            }
        }
        if(pointInfo != null){
            if(pointInfo.baseInfo.getUserId() == 0){
                boolean change = false;
                synchronized (this){
                    //补偿npc血量
                    if(pointInfo.baseInfo.getTotalBlood() == 0 || pointInfo.baseInfo.getObjectInfoList().size() == 0){
                        change = initNpcInfo(resGrab, pointInfo);
                    }
                }
                if(change) {
                    synchronized (resGrab.updateAndAddPointInfoSet) {
                        resGrab.updateAndAddPointInfoSet.add(pointInfo);
                    }
                }
            }
        }
        return pointInfo;
    }

    /**
     * 计算资源 总采集时长
     * @return
     */
    private int calResTotalTime(NewMonopolyMarketResGrab resGrab, int posIndex){
        NewMonopolyMarketResConfigData configData = getMonopolyMarketResConfigData(resGrab, posIndex);
        return (int)(configData.getLimit() * DateHelper.MINUTE_SECONDS);
    }

    /**
     * 根据索引位置获取当前配置的等级  配置
     * @param resGrab
     * @param posIndex
     * @return
     */
    private NewMonopolyMarketResConfigData getMonopolyMarketResConfigData(NewMonopolyMarketResGrab resGrab, int posIndex){
        int level = resGrab.map.indexLevelMap.get(posIndex);
        return CrossNewMonopolyMarketConfigMgr.getMonopolyMarketResConfigData(resGrab.type, level);
    }

    public void synPatrons(NewMonopolyMarketResGrab resGrab, long userId, List<NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity> list){
        Set<NewMonopolyMarketResGrabPointInfo> pointInfos =  resGrab.getUserPointSet(userId,false);
        if(pointInfos != null) {
            for (NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity item : list) {
                for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfos) {
                    NewMonopolyMarketBaseBattleObjectInfo objectInfo = pointInfo.objectInfoMap.get(item.getPatronsId());
                    if (objectInfo != null) {
                        NewMonopolyMarketPatronsInfo patronsInfo = (NewMonopolyMarketPatronsInfo) objectInfo;
                        patronsInfo.setStageLv(item.getStageLv());
                        patronsInfo.setLevel(item.getLevel());
                        patronsInfo.setSkinId(item.getSkinId());
                        patronsInfo.setBase(item.getEarn());
                        patronsInfo.setAddition(item.getAddPlus());
                        pointInfo.baseInfo.setUpdateOption();
                        synchronized (resGrab.updateAndAddPointInfoSet) {
                            resGrab.updateAndAddPointInfoSet.add(pointInfo);
                        }
                        break;
                    }
                }
            }
        }
    }

    public void synBeauty(NewMonopolyMarketResGrab resGrab, long userId, List<NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity> list){
        Set<NewMonopolyMarketResGrabPointInfo> pointInfos =  resGrab.getUserPointSet(userId,false);
        if(pointInfos != null) {
            for (NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity item : list){
                for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfos){
                    NewMonopolyMarketBaseBattleObjectInfo objectInfo = pointInfo.objectInfoMap.get(item.getId());
                    if(objectInfo != null){
                        NewMonopolyMarketBeautyInfo patronsInfo = (NewMonopolyMarketBeautyInfo)objectInfo;

                        patronsInfo.setId(item.getId());
                        patronsInfo.setBase(item.getValue());
                        patronsInfo.setSkinId(item.getSkinId());
                        patronsInfo.setAddition(item.getAddPlus());
                        pointInfo.baseInfo.setUpdateOption();
                        synchronized (resGrab.updateAndAddPointInfoSet) {
                            resGrab.updateAndAddPointInfoSet.add(pointInfo);
                        }
                        break;
                    }
                }
            }
        }
    }

    public static long getTotalValue(NewMonopolyMarketResGrabPointInfo pointInfo){
        long totalValue = 0;
        for (NewMonopolyMarketBaseBattleObjectInfo item : pointInfo.baseInfo.getObjectInfoList()){
            totalValue += item.getBase();
        }
        return totalValue;
    }


    //--------------  每日结算

    /**
     * 尝试结算资源点
     */
    public boolean attemptSettlement(NewMonopolyMarketResGrab resGrab,NewMonopolyMarketResGrabPointInfo pointInfo, int now){
        int endTime = getPointEndTime(resGrab,pointInfo);
        if(endTime != -1 && endTime <= now){
            normalSettlement(resGrab,pointInfo,false, endTime);
            return true;
        }
        return false;
    }

    /**
     * 周二零点，补发奖励
     */
    public void sendResGrabReward(int now){

        int weekId = GameConfig.getSystemThisWeekId();
        if(weekId == this.monopolyMarket.getWeekStateData().getWeekId()){
            return;
        }

        if(monopolyMarket.getWeekStateData().isResGrabReward()){
            return;
        }
        monopolyMarket.getWeekStateData().setResGrabReward(true);
        synchronized (this){

            for (Map.Entry<Long, Map<Long, CrossNewMonopolyMarketUserData>> entry : monopolyMarket.getServerUserDataMap().entrySet()) {
                long serverId = entry.getKey();
                for (Map.Entry<Long, CrossNewMonopolyMarketUserData> userDataEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketUserData userData = userDataEntry.getValue();
                    List<NewMonopolyMarketResGrabFinishData> list = getMonopolyMarketResGrabFinishDataList(userData.getUserId(),false);
                    List<NewMonopolyMarketResGrabFinishData> tempList = new ArrayList<>();
                    if(list != null && list.size() > 0){
                        synchronized (list) {
                            tempList.addAll(list);
                            list.clear();
                        }
                        // 1 清空 入库
                        for (NewMonopolyMarketResGrabFinishData item : tempList){
                            item.setIsReceive(true);
                        }
                        // 入库
                        synchronized (tempResGrabFinishList){
                            tempResGrabFinishList.addAll(tempList);
                        }
                    }
                    if(tempList.size() > 0) {
                        Property property = new Property();
                        for (NewMonopolyMarketResGrabFinishData data : tempList) {
                            if(data.getRewardNum() <= 0){
                                CrossNewMonopolyMarketMgr.getLogger().info("new monopoly send resGrab reward userId {}, resGroupId {}, pos {}, reward null", userData.getUserId(), data.getResGroupId(), data.getPosIndex());
                                continue;
                            }
                            int goodsId = NewMonopolyMarketCommonMgr.getGoodsId(data.getType());
                            property.addProperty(new Property(goodsId, BigInteger.valueOf(data.getRewardNum())));
                        }
                        NewMonopolyMarketProto.NewMonopolyMarketSendResGrabRewardSync.Builder sync = NewMonopolyMarketProto.NewMonopolyMarketSendResGrabRewardSync.newBuilder();
                        sync.setUserId(userData.getUserId());
                        sync.setReward(PropertyHelper.parsePropertyToString(property));
                        MessageHelper.sendPacket(serverId, userData.getUserId(), YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_SEND_RES_GRAB_RANK_REWARD_FROM_CROSS, sync));

                        CrossNewMonopolyMarketMgr.getLogger().info("new monopoly send resGrab reward userId {}, reward {}", userData.getUserId(), sync.getReward());
                    }
                }
            }
        }

    }

    //--------------  每日结算

    //--

    public Map<Integer, NewMonopolyMarketResGrab> getMarketResGrabMap() {
        return marketResGrabMap;
    }

    public NewMonopolyMarketResGrab getNewMonopolyMarketResGrab(int resGroupId){
        return marketResGrabMap.get(resGroupId);
    }

    //

    public static NewMonopolyMarketProto.NewMonopolyMarketAddRankValueEntity.Builder builderMonopolyMarketAddRankValueEntity(NewMonopolyMarketResGrabReceiveResult receiveResult){
        NewMonopolyMarketProto.NewMonopolyMarketAddRankValueEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketAddRankValueEntity.newBuilder();
        builder.setAddValue(receiveResult.getAddValue());
        builder.setStartTime(receiveResult.getStartTime());
        builder.setTime(receiveResult.getTime());
        builder.setType(receiveResult.getType());
        return builder;
    }

    private static NewMonopolyMarketProto.NewMonopolyMarketResGrabUserPointEntity.Builder builderMonopolyMarketResGrabUserPointEntity(NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabUserPointEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabUserPointEntity.newBuilder();
        builder.setType(pointInfo.baseInfo.getType());
        builder.setPosIndex(pointInfo.baseInfo.getPosIndex());
        builder.setProduceRewardLastTime(pointInfo.baseInfo.getProduceRewardLastTime());
        builder.setEndTime(pointInfo.baseInfo.getEndTime());
        builder.setTotalValues(getTotalValue(pointInfo));
        builder.setTotalBlood(pointInfo.baseInfo.getTotalBlood());
        builder.setBlood(pointInfo.baseInfo.getBlood());
        builder.setResGroupId(pointInfo.baseInfo.getResGroupId());
        return builder;
    }

    public static NewMonopolyMarketProto.NewMonopolyMarketResGrabSearchPointEntity.Builder builderMonopolyMarketResGrabSearchPointEntity(NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabSearchPointEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabSearchPointEntity.newBuilder();
        builder.setPosIndex(pointInfo.baseInfo.getPosIndex());
        builder.setResGroupId(pointInfo.baseInfo.getResGroupId());
        if(pointInfo.baseInfo.getUserId() > 0){
            builder.setUserId(pointInfo.baseInfo.getUserId());
            builder.setEndTime(pointInfo.baseInfo.getEndTime());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(pointInfo.baseInfo.getUserId());
            if(userBaseInfo != null){
                builder.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
        }else {
            builder.setRemainTime(pointInfo.baseInfo.getRemainTime());
        }
        return builder;
    }

    /**
     * 队伍数据
     * @param pointInfo
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketGetTeamEntity.Builder builderMonopolyMarketGetTeamEntity(NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketProto.NewMonopolyMarketGetTeamEntity.Builder team = NewMonopolyMarketProto.NewMonopolyMarketGetTeamEntity.newBuilder();
        team.setType(pointInfo.baseInfo.getType());
        team.setPosIndex(pointInfo.baseInfo.getPosIndex());
        team.setEndTime(pointInfo.baseInfo.getEndTime());
        team.setStartTime(pointInfo.baseInfo.getSeatTime());
        team.setReceiveLastTime(pointInfo.baseInfo.getReceiveLastTime());
        team.setProduceRewardLastTime(pointInfo.baseInfo.getProduceRewardLastTime());
        for (NewMonopolyMarketBaseBattleObjectInfo objectInfo : pointInfo.baseInfo.getObjectInfoList()){
            team.addObjectList(objectInfo.getId());
        }
        team.setResGroupId(pointInfo.baseInfo.getResGroupId());
        team.setTotalBlood(pointInfo.baseInfo.getTotalBlood());
        team.setBlood(pointInfo.baseInfo.getBlood());
        return team;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketResGrabPointEntity.Builder builderMonopolyMarketResGrabPointEntity(NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabPointEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabPointEntity.newBuilder();
        builder.setPosIndex(pointInfo.baseInfo.getPosIndex());
        if(pointInfo.baseInfo.getUserId() > 0){
            builder.setUserId(pointInfo.baseInfo.getUserId());
            builder.setEndTime(pointInfo.baseInfo.getEndTime());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(pointInfo.baseInfo.getUserId());
            if(userBaseInfo != null){
                builder.setUserName(userBaseInfo.getNickName());
                builder.setUnionId(userBaseInfo.getUnionUid());
            }
            builder.setRemainTime(pointInfo.baseInfo.getRemainTime());
        }else {
            builder.setRemainTime(pointInfo.baseInfo.getRemainTime());
        }
        builder.setTotalBlood(pointInfo.baseInfo.getTotalBlood());
        builder.setBlood(pointInfo.baseInfo.getBlood());
        return builder;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketResGrabPointDetailEntity.Builder builderMonopolyMarketResGrabPointDetailEntity(NewMonopolyMarketResGrabPointInfo pointInfo){
        NewMonopolyMarketProto.NewMonopolyMarketResGrabPointDetailEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabPointDetailEntity.newBuilder();
        builder.setPosIndex(pointInfo.baseInfo.getPosIndex());
        builder.setUserId(pointInfo.baseInfo.getUserId());
        builder.setTotalBlood(pointInfo.baseInfo.getTotalBlood());
        builder.setBlood(pointInfo.baseInfo.getBlood());
        if(pointInfo.baseInfo.getUserId() > 0){
            builder.setUserId(pointInfo.baseInfo.getUserId());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(pointInfo.baseInfo.getUserId());
            if(userBaseInfo != null){
                builder.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
            builder.setTotalValues(getTotalValue(pointInfo));
            builder.setProduceRewardLastTime(pointInfo.baseInfo.getProduceRewardLastTime());
            builder.setStartTime(pointInfo.baseInfo.getSeatTime());
            builder.setEndTime(pointInfo.baseInfo.getEndTime());
            builder.setRemainTime(pointInfo.baseInfo.getRemainTime());
        }else {
            builder.setRemainTime(pointInfo.baseInfo.getRemainTime());
        }
        if(pointInfo.baseInfo.getUserId() > 0 && pointInfo.baseInfo.getServerId() == 0){
            UserBaseInfo baseInfo = CrossUserMgr.getUserBaseInfo(pointInfo.baseInfo.getUserId());
            if(baseInfo != null){
                pointInfo.baseInfo.setServerId(baseInfo.getServerId());
            }
        }
        builder.setServerId(pointInfo.baseInfo.getServerId());
        builder.setResGroupId(pointInfo.baseInfo.getResGroupId());
        return builder;
    }
}
